package com.sunday.common.mq.kafka.study.spring.e9_Producer_Consumer_Interceptors;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CompletableFuture;

/**
 * {@link org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration}
 */
@Slf4j
@RestController
@RequestMapping("/test")
public class MQApi {

    @Autowired
    private KafkaTemplate<Object, Object> kafkaTemplate;

    @GetMapping("/send/{topic}/{key}")
    public void send(@PathVariable String topic, @PathVariable String key) {
        CompletableFuture<SendResult<Object, Object>> future;
        future = kafkaTemplate.send(topic, key, key);
        future.whenComplete((result, throwable) -> log.info("[{}] result : {}, throwable : {}", topic, result, throwable));
    }

    @GetMapping("/batch/{topic}")
    public void batch(@PathVariable String topic) {
        CompletableFuture<SendResult<Object, Object>> future;
        for (int i = 0; i < 10; i++) {
            future = kafkaTemplate.send(topic, i + "", i + "");
            future.whenComplete((result, throwable) -> log.info("[{}] result : {}, throwable : {}", topic, result, throwable));
        }
    }

    @KafkaListener(
            id = "myId_6",
            topics = "topic6",
            clientIdPrefix = "TEST"
    )
    public void listen6(String in) {
        log.info("======================== {}", in);
    }


}
